package org.lc.oauth.config;


import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.lc.oauth.extension.handler.AuthEntryPointHandler;
import org.lc.oauth.extension.handler.MyAuthenticationFailureHandler;
import org.lc.oauth.extension.handler.MyAuthenticationSuccessHandler;
import org.lc.oauth.extension.password.PasswordAuthenticationConverter;
import org.lc.oauth.extension.password.PasswordAuthenticationProvider;
import org.lc.oauth.extension.password.PasswordAuthenticationToken;
import org.lc.oauth.jackson.SysUserMixin;
import org.lc.oauth.util.JwtUtil;
import org.lc.oauth.vo.LcUserDetails;
import org.lc.oauth.util.Sm4PasswordEncoder;
import org.lc.platform.base.constant.AuthConstant;
import org.lc.platform.oauth2.properties.SecurityOauth2Properties;
import org.lc.platform.redis.service.CacheService;
import org.lc.service.system.client.feign.IUserFeign;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.lob.DefaultLobHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.ClientAuthenticationMethod;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.JdbcOAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationConsentService;
import org.springframework.security.oauth2.server.authorization.OAuth2AuthorizationService;
import org.springframework.security.oauth2.server.authorization.client.JdbcRegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configuration.OAuth2AuthorizationServerConfiguration;
import org.springframework.security.oauth2.server.authorization.config.annotation.web.configurers.OAuth2AuthorizationServerConfigurer;
import org.springframework.security.oauth2.server.authorization.jackson2.OAuth2AuthorizationServerJackson2Module;
import org.springframework.security.oauth2.server.authorization.settings.AuthorizationServerSettings;
import org.springframework.security.oauth2.server.authorization.settings.ClientSettings;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.authorization.token.*;
import org.springframework.security.web.SecurityFilterChain;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Duration;
import java.util.List;

@Configuration
@RequiredArgsConstructor
@Slf4j
public class AuthorizationServerConfig {

    private final OAuth2TokenCustomizer<JwtEncodingContext> jwtCustomizer;

    private final SecurityOauth2Properties authProperties;

    private final CacheService cacheService;

    private final JwtUtil jwtUtil;

    private final PasswordEncoder passwordEncoder;
    private final IUserFeign iUserFeign;

    /**
     * 授权服务器端点配置
     */
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SecurityFilterChain authorizationServerSecurityFilterChain(
            HttpSecurity http,
            AuthenticationManager authenticationManager,
            OAuth2AuthorizationService authorizationService,
            OAuth2TokenGenerator<?> tokenGenerator

    ) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)

                // 自定义授权模式转换器(Converter)
                .tokenEndpoint(tokenEndpoint -> tokenEndpoint
                        .accessTokenRequestConverters(
                                authenticationConverters -> // <1>
                                        // 自定义授权模式转换器(Converter)
                                        authenticationConverters.add(
                                                new PasswordAuthenticationConverter()
                                        )
                        )
                        .authenticationProviders(
                                authenticationProviders -> // <2>
                                        // 自定义授权模式提供者(Provider)
                                        authenticationProviders.add(
                                                new PasswordAuthenticationProvider(authenticationManager, authorizationService, tokenGenerator)
                                        )
                        )
                        .accessTokenResponseHandler(new MyAuthenticationSuccessHandler(cacheService, jwtUtil, iUserFeign)) // 自定义成功响应
                        .errorResponseHandler(new MyAuthenticationFailureHandler()) // 自定义失败响应

                );


        http
                .exceptionHandling((exceptions) -> exceptions.authenticationEntryPoint(new AuthEntryPointHandler())
                )
                .oauth2ResourceServer(oauth2ResourceServer ->
                        oauth2ResourceServer.jwt(Customizer.withDefaults()));


        return http.build();
    }


    @Bean
    public RegisteredClientRepository registeredClientRepository(JdbcTemplate jdbcTemplate) {
        JdbcRegisteredClientRepository registeredClientRepository = new JdbcRegisteredClientRepository(jdbcTemplate);

        // 初始化 OAuth2 客户端
        initMallAdminClient(registeredClientRepository);

        return registeredClientRepository;
    }

    @Bean
    public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate,
                                                           RegisteredClientRepository registeredClientRepository) {

        /* 创建基于JDBC的OAuth2授权服务。这个服务使用JdbcTemplate和客户端仓库来存储和检索OAuth2授权数据。*/
        JdbcOAuth2AuthorizationService service = new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);

        /* 创建并配置用于处理数据库中OAuth2授权数据的行映射器。 */
        JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper rowMapper = new JdbcOAuth2AuthorizationService.OAuth2AuthorizationRowMapper(registeredClientRepository);
        rowMapper.setLobHandler(new DefaultLobHandler());
        ObjectMapper objectMapper = new ObjectMapper();
        ClassLoader classLoader = JdbcOAuth2AuthorizationService.class.getClassLoader();
        List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader);
        securityModules.forEach(modules -> {
            if (modules != null) {
                objectMapper.registerModules(modules);
            }
        });
        objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
        /* 添加自定义Mixin，用于序列化/反序列化特定的类。 */
        /* Mixin类需要自行实现，以便Jackson可以处理这些类的序列化。 */
        objectMapper.addMixIn(LcUserDetails.class, SysUserMixin.class);
        objectMapper.addMixIn(Long.class, Object.class);
        /* 将配置好的ObjectMapper设置到行映射器中。 */
        rowMapper.setObjectMapper(objectMapper);

        /* 将自定义的行映射器设置到授权服务中。 */
        service.setAuthorizationRowMapper(rowMapper);
        return service;
    }

    @Bean
    public OAuth2AuthorizationConsentService authorizationConsentService(JdbcTemplate jdbcTemplate,
                                                                         RegisteredClientRepository registeredClientRepository) {
        // Will be used by the ConsentController
        return new JdbcOAuth2AuthorizationConsentService(jdbcTemplate, registeredClientRepository);
    }

    @Bean
    OAuth2TokenGenerator<?> tokenGenerator(JWKSource<SecurityContext> jwkSource) {
        JwtGenerator jwtGenerator = new JwtGenerator(new NimbusJwtEncoder(jwkSource));
        jwtGenerator.setJwtCustomizer(jwtCustomizer);

        OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
        OAuth2RefreshTokenGenerator refreshTokenGenerator = new OAuth2RefreshTokenGenerator();
        return new DelegatingOAuth2TokenGenerator(
                jwtGenerator, accessTokenGenerator, refreshTokenGenerator);
    }


    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
        return authenticationConfiguration.getAuthenticationManager();
    }

    private void initMallAdminClient(JdbcRegisteredClientRepository registeredClientRepository) {

        String clientId = "dl-admin";
        String clientSecret = UUID.randomUUID(false).toString();
        String clientName = "自定义后端管理";
        String encodeSecret = passwordEncoder.encode(clientSecret);
        RegisteredClient registeredMallAdminClient = registeredClientRepository.findByClientId(clientId);
        if (registeredMallAdminClient == null) {
            RegisteredClient mallAppClient = RegisteredClient.withId(UUID.randomUUID().toString())
                    .clientId(clientId)
                    .clientSecret(encodeSecret)
                    .clientName(clientName)
                    .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
                    .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
                    .authorizationGrantType(AuthorizationGrantType.REFRESH_TOKEN)
                    .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
                    .authorizationGrantType(PasswordAuthenticationToken.PASSWORD) // 密码模式
                    .scope("all")
                    .redirectUri("http://127.0.0.1:8080/authorized")
                    .tokenSettings(
                            TokenSettings
                                    .builder()
                                    /* access_token 过期时间 */
                                    .accessTokenTimeToLive(Duration.ofSeconds(authProperties.getExp()))
                                    /* refresh_token 过期时间 */
                                    .refreshTokenTimeToLive(Duration.ofSeconds(authProperties.getRefreshExp()))
                                    .build()
                    )
                    .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
                    .build();

            registeredClientRepository.save(mallAppClient);
        }

    }

}